// 主页头组件
// base
require("../../both/base.js");

// css
require("./UserHeader.scss");

import Popup from "../../both/Popup/Popup.jsx"

function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

class UserHeader extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            modalState : false,
            email : "",
            password : ""
        }
    }

    handleLogin(event) {
        event.preventDefault()

        // 如果已经登录，则是注销
        if(this.props.logined){
            delCookie("LoginToken")
            location.href = location.href.replace(/\#.*/,"")
        }else{
            this.setState({
                modalState : true
            })
        }

    }

    changeInput(name,e){
        var change = {}
        change[name] = e.target.value
        this.setState(change)
    }

    goRegister(){
        this.hideModal()
        var $ = jQuery
        var $target = $("#register");
        $target = $target.length && $target || $('[name=' + "register" + ']');
        if ($target.length) {
            var targetOffset = $target.offset().top;
            $('html,body').animate({
                    scrollTop: targetOffset
                },
                1000);
        }
    }


    hideModal(){
        this.setState({
            modalState : false
        })
    }

    submitLogin(e){
        e.preventDefault()

        var self = this
        if(self.state.email == "" || self.state.password == ""){
            toastr.warning("用户名或密码不能为空")
            return
        }
        fetch("/education/user/login",{
            method: 'POST',
            body:   JSON.stringify({
                email : self.state.email.trim(),
                password : self.state.password.trim()
            }),
            headers: { 'Content-Type': 'application/json' },
            credentials : "same-origin"
        })
            .then(res => res.json())
            .then(json => {
                if(json.status == 403){
                    toastr.error("用户名或密码错误")
                    return
                }

                var LoginToken = json.msg.LoginToken
                setCookie("LoginToken",LoginToken)
                toastr.success("登录成功")
                location.href = location.href.replace(/\#.*/,"")
            })
    }

    render(){
        const handleLogin = this.handleLogin.bind(this)
        const hideModal = this.hideModal.bind(this)
        const goRegister = this.goRegister.bind(this)
        const submitLogin = this.submitLogin.bind(this)

        var isVideoHeader = this.props.isVideoHeader;
        return (
            <div className={this.props.reverse ? "header_container bln reverse" : "header_container bln normal"}>
                <div className={ isVideoHeader ? "fl video" : "fl" } >
                    {
                        isVideoHeader ? <div>
                            <a href="javascript:history.back(1)"><i className="fa fa-chevron-left"></i></a>
                            <div className="title">{this.props.title}</div>
                                <div className="description">{this.props.description}</div>
                        </div> :
                            <div><a href="/home"><i className="logo"></i></a>
                                <ul className="banner">
                                    <li><a href="">实战</a></li>
                                    <li><a href="">路径</a></li>
                                    <li><a href="">猿问</a></li>
                                    <li><a href="">手记</a></li>
                                </ul></div>
                    }
                </div>
                <div className="fr">
                    <ul className="banner_r">
                        {
                            isVideoHeader ? null : <li>
                                <div className="banner_search">
                                    <input type="text" className="banner_search_input"/>
                                    <i className="icon_search fa fa-search"></i>
                                    <div className="badge_cr">
                                        <span className="search_badge">电商</span>
                                        <span className="search_badge">Python</span>
                                    </div>
                                </div>
                            </li>
                        }
                        <li>
                            <i className="app_download fa fa-mobile-phone"></i>
                        </li>
                        {
                            this.props.logined ?
                                <li><div className="mooc-right">
                                    <a href="/personal_center" className="personal_center">
                                        <div className="mooc-welcome">
                                            欢迎&nbsp;{this.props.username}
                                        </div>
                                        <img className="mooc-avatar" src={this.props.avatar} />
                                    </a>
                                </div></li> : null
                        }
                        {
                            this.props.logined ?
                                <li>
                                    <a href="javascript:void(0)" onClick={handleLogin}>注销</a>
                                </li> : null

                        }
                        {
                            this.props.logined ? null :
                                <li>
                                    <a href="javascript:void(0)" onClick={handleLogin}>登录</a>
                                </li>
                        }
                        {
                            this.props.logined ? null : <li>
                                    <a href="/#register">注册</a>
                                </li>
                        }
                    </ul>
                </div>

                <Popup show={this.state.modalState} onCancel={hideModal} showCtrl={false} showHeader={false} title="登录" isFluid={true}>
                    <div className="login_header">
                        <div className="left">
                            <div className="logo"></div>
                            <span className="logo_name">BAG</span>
                            <span className="login_hint">&nbsp;登录</span>
                        </div>
                        <div className="right">
                            <div className="register_hint">还没有帐号？</div>
                            <a className="register_btn" href="/#register" onClick={goRegister}>快速注册</a>
                            <i className="fa fa-close" onClick={hideModal}/>
                        </div>
                    </div>
                    <div className="panel_body">
                        <form className="login_form" onSubmit={submitLogin}>
                            <div className="input_wr">
                                <i className="fa fa-envelope" />
                                <input type="text"
                                       name="email"
                                       className="login_input"
                                       value={this.state.email}
                                       onChange={this.changeInput.bind(this,"email")}
                                       placeholder="请输入登录邮箱"
                                />
                                <div className="input_border" />
                            </div>
                            <div className="input_wr">
                                <i className="fa fa-key" />
                                <input type="password"
                                       name="password"
                                       className="login_input"
                                       value={this.state.password}
                                       onChange={this.changeInput.bind(this,"password")}
                                       placeholder="6-16位密码"
                                />
                                <div className="input_border" />
                            </div>
                            <input type="submit" style={{display:"none"}}/>
                            <div type="submit" className="login_btn" onClick={submitLogin}>
                                登录
                            </div>
                        </form>
                    </div>
                </Popup>

            </div>
        )
    }
}

export default UserHeader;